package xyz.xpman.prisonerfitness.activity;

import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.EditText;

import androidx.annotation.RequiresApi;

import java.util.Objects;

import xyz.xpman.prisonerfitness.R;
import xyz.xpman.prisonerfitness.activity.base.BaseActivity;
import xyz.xpman.prisonerfitness.entity.User;
import xyz.xpman.prisonerfitness.service.UserService;
import xyz.xpman.prisonerfitness.util.StrKit;
import xyz.xpman.prisonerfitness.util.ToastUtil;

/**
 * default user: root , passwd: hello-0797!, id: 666666
 */
public class LoginActivity extends BaseActivity {
    private UserService service;
    private EditText username, password;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        service = UserService.ME;

        init();
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void init() {
        username = findViewById(R.id.username);
        password = findViewById(R.id.password);

        // 登录事件
        findViewById(R.id.login).setOnClickListener(view-> {
            String message = login();

            if (StrKit.isBlank(message)) {
                ToastUtil.showText(this, "登录成功!");
                finish();
                return;
            }

            ToastUtil.showText(this, message);
        });


        // 跳转注册事件
        findViewById(R.id.link_to_register).setOnClickListener(view->
                toActivity(RegisterActivity.class));

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private String login() {
        String username = this.username.getText().toString();
        String password = this.password.getText().toString();

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        return service.loginByUsernameAndPassword(user);
    }



    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return processMenuItemForBack(item);
    }

}